package com.digitalbuana.smiles.activity;

import java.util.Collection;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.digitalbuana.smiles.R;
import com.digitalbuana.smiles.adapter.LeftMenuAdapter;
import com.digitalbuana.smiles.data.ActivityManager;
import com.digitalbuana.smiles.data.AppConstants;
import com.digitalbuana.smiles.data.Application;
import com.digitalbuana.smiles.data.NetworkException;
import com.digitalbuana.smiles.data.SettingsManager;
import com.digitalbuana.smiles.data.account.OnAccountChangedListener;
import com.digitalbuana.smiles.data.entity.BaseEntity;
import com.digitalbuana.smiles.data.extension.avatar.AvatarManager;
import com.digitalbuana.smiles.data.extension.muc.MUCManager;
import com.digitalbuana.smiles.data.extension.vcard.VCardManager;
import com.digitalbuana.smiles.data.intent.EntityIntentBuilder;
import com.digitalbuana.smiles.data.message.OnChatChangedListener;
import com.digitalbuana.smiles.data.roster.AbstractContact;
import com.digitalbuana.smiles.data.roster.OnContactChangedListener;
import com.digitalbuana.smiles.ui.adapter.AccountToggleAdapter;
import com.digitalbuana.smiles.ui.adapter.ContactListAdapter;
import com.digitalbuana.smiles.ui.adapter.GroupConfiguration;
import com.digitalbuana.smiles.ui.dialog.ConfirmDialogListener;
import com.digitalbuana.smiles.ui.dialog.DialogBuilder;
import com.digitalbuana.smiles.ui.helper.BaseUIListActivity;
import com.digitalbuana.smiles.ui.widget.GridViewKu;
import com.digitalbuana.smiles.utils.FontUtils;
import com.digitalbuana.smiles.utils.ViewUtilities;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.slidingmenu.lib.SlidingMenu;

public class HomeActivity extends BaseUIListActivity implements
OnContactChangedListener, OnAccountChangedListener,
OnChatChangedListener, View.OnClickListener, ConfirmDialogListener,
OnItemClickListener, OnLongClickListener{
	
	//HomeContainer
	//Title
	private FrameLayout btnShowMenu;
	private FrameLayout btnShowEntertaint;
	
	//Content
	LinearLayout homeContainer;
	SlidingMenu slidingMenu;
	ListView listView;
	
	//Start Container
	private FrameLayout startContainer;
	private ImageView imgTopLogo;
	private ImageView imgCewe;
	private FrameLayout btnRegister;
	private FrameLayout btnLogin;
	
	//LeftMenuCotainer
	private LinearLayout leftMenuTitle;
	private ImageView leftMenuAvatar;
	private TextView leftMenuUser;
	private TextView leftMenuStatus;
	private ListView leftMenuList;
	private LeftMenuAdapter leftMenuAdapter;
	
	//LeftMenuCotainer
	private GridViewKu rightMenuMultimedia;
	private GridViewKu rightMenuContent;
	private FrameLayout rightMenuAdsConteiner;
	private FrameLayout rightMenuShopConteiner;
	
	private ContactListAdapter contactListAdapter;
	private AccountToggleAdapter accountToggleAdapter;
	private static final String ACTION_ROOM_INVITE = "com.digitalbuana.smiles.activity.HomeActivity.ACTION_ROOM_INVITE";
	
	private static final String SAVED_ACTION = "com.digitalbuana.smiles.activity.HomeActivity.SAVED_ACTION";
	private static final String SAVED_ACTION_WITH_ACCOUNT = "com.digitalbuana.smiles.activity.HomeActivity.SAVED_ACTION_WITH_ACCOUNT";
	private static final String SAVED_ACTION_WITH_GROUP = "com.digitalbuana.smiles.activity.HomeActivity.SAVED_ACTION_WITH_GROUP";
	private static final String SAVED_ACTION_WITH_USER = "com.digitalbuana.smiles.activity.HomeActivity.SAVED_ACTION_WITH_USER";
	private static final String SAVED_SEND_TEXT = "com.digitalbuana.smiles.activity.HomeActivity.SAVED_SEND_TEXT";
	private static final String SAVED_OPEN_DIALOG_USER = "com.digitalbuana.smiles.activity.HomeActivity.SAVED_OPEN_DIALOG_USER";
	private static final String SAVED_OPEN_DIALOG_TEXT = "com.digitalbuana.smiles.activity.HomeActivity.SAVED_OPEN_DIALOG_TEXT";
	private String action;
	private String actionWithAccount;
	private String actionWithGroup;
	private String actionWithUser;
	private String sendText;
	private String openDialogUser;
	private String openDialogText;
	
	public void onCreate(Bundle savedInstanceState) {
		if (Intent.ACTION_VIEW.equals(getIntent().getAction())
				|| Intent.ACTION_SEND.equals(getIntent().getAction())
				|| Intent.ACTION_SENDTO.equals(getIntent().getAction())
				|| Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction()))
			ActivityManager.getInstance().startNewTask(this);
		super.onCreate(savedInstanceState);
		if (isFinishing()){return;};
		setContentView(R.layout.activity_home);
		//Casting
		rootView = (FrameLayout)findViewById(R.id.homeRootView);

		//Casting
		//HomeContainer
		//title
		btnShowMenu = (FrameLayout)findViewById(R.id.homeTitleBtnShowMenu);
		btnShowEntertaint = (FrameLayout)findViewById(R.id.homeTitleBtnShowEntertaint);
		
		homeContainer = (LinearLayout)findViewById(R.id.homeContainer);
		listView =  getListView();
		
		//StartContainer
		startContainer = (FrameLayout)findViewById(R.id.homeStartContainer);
		imgTopLogo = (ImageView) findViewById(R.id.homeStartImgTopLogo);
		imgCewe = (ImageView) findViewById(R.id.homeStartCewe);
		btnRegister= (FrameLayout)findViewById(R.id.homeStartBtnRegister);
		btnLogin = (FrameLayout)findViewById(R.id.homeStartBtnLogin);
		

		registerForContextMenu(listView);
		contactListAdapter = new ContactListAdapter(this);
		setListAdapter(contactListAdapter);
		
		settingSlidingMenu();
		//SettingListenr
		btnShowMenu.setOnClickListener(this);
		btnShowEntertaint.setOnClickListener(this);
		leftMenuTitle.setOnClickListener(this);
		listView.setOnItemClickListener(this);
		listView.setItemsCanFocus(true);
		//StartView
		btnLogin.setOnClickListener(this);
		btnRegister.setOnClickListener(this);
		
		//LeftMenu
		leftMenuList.setOnItemClickListener(this);
		//RightMenu
		rightMenuMultimedia.setOnItemClickListener(this);
		rightMenuContent.setOnItemClickListener(this);
		rightMenuShopConteiner.setOnClickListener(this);
		
		accountToggleAdapter = new AccountToggleAdapter(this, leftMenuTitle);
		
		FontUtils.setRobotoFont(context, rootView);
		if (savedInstanceState != null) {
			actionWithAccount = savedInstanceState.getString(SAVED_ACTION_WITH_ACCOUNT);
			actionWithGroup = savedInstanceState.getString(SAVED_ACTION_WITH_GROUP);
			actionWithUser = savedInstanceState.getString(SAVED_ACTION_WITH_USER);
			sendText = savedInstanceState.getString(SAVED_SEND_TEXT);
			openDialogUser = savedInstanceState.getString(SAVED_OPEN_DIALOG_USER);
			openDialogText = savedInstanceState.getString(SAVED_OPEN_DIALOG_TEXT);
			action = savedInstanceState.getString(SAVED_ACTION);
		} else {
			actionWithAccount = null;
			actionWithGroup = null;
			actionWithUser = null ;
			sendText = null;
			openDialogUser = null;
			openDialogText = null;
			action = getIntent().getAction();
		}
		getIntent().setAction(null);
	}
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		action = getIntent().getAction();
		getIntent().setAction(null);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(SAVED_ACTION, action);
		outState.putString(SAVED_ACTION_WITH_ACCOUNT, actionWithAccount);
		outState.putString(SAVED_ACTION_WITH_GROUP, actionWithGroup);
		outState.putString(SAVED_ACTION_WITH_USER, actionWithUser);
		outState.putString(SAVED_SEND_TEXT, sendText);
		outState.putString(SAVED_OPEN_DIALOG_USER, openDialogUser);
		outState.putString(SAVED_OPEN_DIALOG_TEXT, openDialogText);
	}

	private void settingAds(){
		AdView adView = new AdView(this, AdSize.BANNER, AppConstants.AdMobIDHome);
		rightMenuAdsConteiner.addView(adView);
		AdRequest request = new AdRequest();
		adView.loadAd(request);
	}
	
	private void settingSlidingMenu()
	{
		slidingMenu = new SlidingMenu(this);
		slidingMenu.setMode(SlidingMenu.LEFT_RIGHT);
		slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
		slidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
		slidingMenu.setMenu(R.layout.activity_home_leftmenu);
		slidingMenu.setSecondaryMenu(R.layout.activity_home_rightmenu);
		slidingMenu.setFadeDegree(0);
		slidingMenu.setBehindScrollScale(0.5f);
		slidingMenu.setBehindWidth(ViewUtilities.GetInstance().convertDPtoPX(context, 320));
		leftMenuTitle = (LinearLayout)slidingMenu.getMenu().findViewById(R.id.homeLeftMenuTitle);
		leftMenuAvatar = (ImageView)slidingMenu.getMenu().findViewById(R.id.avatar);
		leftMenuUser = (TextView)slidingMenu.getMenu().findViewById(R.id.homeLeftMenuTitleName);
		leftMenuStatus  = (TextView)slidingMenu.getMenu().findViewById(R.id.homeLeftMenuTitleStatus);
		leftMenuList = (ListView)slidingMenu.getMenu().findViewById(R.id.homeLeftMenuList); 
		//RightMenu
		rightMenuMultimedia = (GridViewKu)slidingMenu.getSecondaryMenu().findViewById(R.id.homeRightMenuMultimediaGrid);
		rightMenuContent = (GridViewKu)slidingMenu.getSecondaryMenu().findViewById(R.id.homeRightMenuContentGrid);
		rightMenuAdsConteiner = (FrameLayout)slidingMenu.getSecondaryMenu().findViewById(R.id.homeRightMenuAdsContainer);
		rightMenuShopConteiner = (FrameLayout)slidingMenu.getSecondaryMenu().findViewById(R.id.homeRightMenuShopContainer);
		
		leftMenuAdapter = new LeftMenuAdapter(this);
		leftMenuList.setAdapter(leftMenuAdapter);
		
		FontUtils.setRobotoFont(context, slidingMenu.getMenu());
		FontUtils.setRobotoFont(context, slidingMenu.getSecondaryMenu());
		settingAds();
		
		final ImageView kakatuaView = (ImageView)findViewById(R.id.kakatuaKuimgProgress);
		kakatuaView.setBackgroundResource(R.drawable.kakatua_junior_anim);
		kakatuaView.post(new Runnable() {
			@Override
			public void run() {
				AnimationDrawable anim = (AnimationDrawable) kakatuaView.getBackground();
		        anim.start();
			}
		});
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		resettingView();
		rebuildAccountToggler();
		
		Application.getInstance().addUIListener(OnAccountChangedListener.class, this);
		Application.getInstance().addUIListener(OnContactChangedListener.class, this);
		Application.getInstance().addUIListener(OnChatChangedListener.class, this);
		contactListAdapter.onChange();
		contactListAdapter.refreshRequest();
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	
	private void rebuildAccountToggler() {
		accountToggleAdapter.rebuildAccount(leftMenuAvatar, leftMenuUser, leftMenuStatus);
		
		if (SettingsManager.contactsShowPanel() && accountToggleAdapter.getCount() > 0)
		{
			slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
			homeContainer.setVisibility(View.VISIBLE);
		} else {
			slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
			homeContainer.setVisibility(View.GONE);
		}
	}
	
	
	
	
	@Override
	protected void onPause() {
		super.onPause();
		unregisterListeners();
	}

	private void unregisterListeners() {
		Application.getInstance().removeUIListener(OnAccountChangedListener.class, this);
		Application.getInstance().removeUIListener(OnContactChangedListener.class, this);
		Application.getInstance().removeUIListener(OnChatChangedListener.class, this);
		contactListAdapter.removeRefreshRequests();
	}
	
	@Override
	protected void resettingView() {
		super.resettingView();
		if(homeContainer.getVisibility()==View.VISIBLE){
			int widthku = ViewUtilities.GetInstance().convertDPtoPX(context, 320);
			if(viewWidth<=widthku){
				slidingMenu.setBehindWidth(viewWidth);
			}
		}
		if(startContainer.getVisibility()==View.VISIBLE){
			int tempHeight = viewHeight-90;
			imgTopLogo.getLayoutParams().height = (tempHeight*17)/100;
			imgCewe.getLayoutParams().height = (tempHeight*66)/100;
			if(ViewUtilities.GetInstance().isLandscape()){
				imgCewe.setImageResource(R.drawable.img_start_cewe_landscape);
			}else {
				imgCewe.setImageResource(R.drawable.img_start_cewe);
			}
		}

	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			onBackPressed();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}
	
	@Override
	public void onBackPressed() {
		if(slidingMenu.isMenuShowing()||slidingMenu.isSecondaryMenuShowing()){
			slidingMenu.showContent();
		} else {
			finish();
		}
	}

	public static Intent createPersistentIntent(Context context) {
		Intent intent = new Intent(context, HomeActivity.class);
		intent.setAction("android.intent.action.MAIN");
		intent.addCategory("android.intent.category.LAUNCHER");
		intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
		return intent;
	}
	public static Intent createIntent(Context context) {
		return new Intent(context, HomeActivity.class);
	}
	public static Intent createRoomInviteIntent(Context context,String account, String room) {
		Intent intent = new EntityIntentBuilder(context, HomeActivity.class).setAccount(account).setUser(room).build();
		intent.setAction(ACTION_ROOM_INVITE);
		return intent;
	}
	
	@Override
	public void onCancel(DialogBuilder dialogBuilder) {
		
	}

	@Override
	public void onDecline(DialogBuilder dialogBuilder) {
		
	}

	@Override
	public void onAccept(DialogBuilder dialogBuilder) {
		
	}

	@Override
	public boolean onLongClick(View arg0) {
		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if(parent==leftMenuList){
		if(((LeftMenuAdapter.ViewHolder)view.getTag()).isSelectable()){
			switch (position){
			case 0:break;
			case 1:startActivity(BroadcastMesssageActivity.createIntent(this));slidingMenu.showContent();break;
			case 2:startActivity(AddFriendsActivity.createIntent(this));slidingMenu.showContent();break;
			case 3:startActivity(CreateGroupActivity.createIntent(this));slidingMenu.showContent();break;
			case 4:startActivity(FriendsRequestActivity.createIntent(this));slidingMenu.showContent();break;
			case 5:startActivity(BlockedFriendsActivity.createIntent(this));slidingMenu.showContent();break;
			case 6:startActivity(FriendsUpdateActivity.createIntent(this));slidingMenu.showContent();break;
			case 7:startActivity(VisitorActivity.createIntent(this));slidingMenu.showContent();break;
			case 8:startActivity(NotificationActivity.createIntent(this));slidingMenu.showContent();break;
			case 9:startActivity(RoomsActivity.createIntent(this));slidingMenu.showContent();break;
			case 10:startActivity(SettingsActivity.createIntent(this));slidingMenu.showContent();break;
			}
			//LeftMenuAdapter.indexLeftMenuPos= position;
			//eftMenuAdapter.notifyDataSetChanged();
		}
		} else {
			Object object = parent.getAdapter().getItem(position);
			if (object == null) {
				// Account toggler
			} else if (object instanceof AbstractContact) {
				AbstractContact abstractContact = (AbstractContact) object;
				if (ACTION_ROOM_INVITE.equals(action)) {
					action = null;
					Intent intent = getIntent();
					String account = getRoomInviteAccount(intent);
					String user = getRoomInviteUser(intent);
					if (account != null && user != null)
						try {
							MUCManager.getInstance().invite(account, user, abstractContact.getUser());
						} catch (NetworkException e) {
							Application.getInstance().onError(e);
						}
					finish();
				} else if (Intent.ACTION_SEND.equals(action)) {
					action = null;
					startActivity(ChatViewer.createSendIntent(this,
							abstractContact.getAccount(),
							abstractContact.getUser(), sendText));
					finish();
				} else if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
					Intent intent = new Intent();
					intent.putExtra(
							Intent.EXTRA_SHORTCUT_INTENT,
							ChatViewer.createClearTopIntent(this,
									abstractContact.getAccount(),
									abstractContact.getUser()));
					intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,abstractContact.getName());
					Bitmap bitmap;
					if (MUCManager.getInstance().hasRoom(abstractContact.getAccount(),abstractContact.getUser()))
						bitmap = AvatarManager.getInstance().getRoomBitmap(abstractContact.getUser());
					else
						bitmap = AvatarManager.getInstance().getUserBitmap(abstractContact.getUser());
						intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, AvatarManager.getInstance().createShortcutBitmap(bitmap));
					setResult(RESULT_OK, intent);
					finish();
				} else {
					startActivity(ChatViewer.createIntent(this, abstractContact.getAccount(),abstractContact.getUser()));
				}
			} else if (object instanceof GroupConfiguration) {
				GroupConfiguration groupConfiguration = (GroupConfiguration) object;
				contactListAdapter.setExpanded(groupConfiguration.getAccount(),groupConfiguration.getUser(),!groupConfiguration.isExpanded());
			}	
		}
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (SettingsManager.contactsShowPanel() && accountToggleAdapter.getCount() > 0)
		{
			if(slidingMenu.isMenuShowing()){
				slidingMenu.showContent(true);
			}else if(slidingMenu.isSecondaryMenuShowing()){
				slidingMenu.showMenu(true);
			}else {
				slidingMenu.showMenu(true);
			}
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.homeTitleBtnShowMenu: slidingMenu.showMenu(true);break;
		case R.id.homeTitleBtnShowEntertaint: slidingMenu.showSecondaryMenu(true);break;
		case R.id.homeLeftMenuTitle:startActivity(ProfileSettingsActivity.createIntent(this));break;
		case R.id.homeStartBtnLogin:startActivity(LoginActivity.createIntent(this));break;
		case R.id.homeStartBtnRegister:startActivity(RegisterActivity.createIntent(this));break;
		}
	}

	@Override
	public void onChatChanged(String account, String user, boolean incoming) {
		if (incoming){
			contactListAdapter.refreshRequest();
		}
	}

	@Override
	public void onAccountsChanged(Collection<String> accounts) {
		accountToggleAdapter.rebuildView(leftMenuAvatar, leftMenuUser, leftMenuStatus);
		contactListAdapter.refreshRequest();
		rebuildAccountToggler();
	}

	@Override
	public void onContactsChanged(Collection<BaseEntity> entities) {
		contactListAdapter.refreshRequest();
	}
	
	private static String getRoomInviteAccount(Intent intent) {
		return EntityIntentBuilder.getAccount(intent);
	}

	private static String getRoomInviteUser(Intent intent) {
		return EntityIntentBuilder.getUser(intent);
	}
}
